package com.pig4cloud.pigx.gateway;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 这里省略了编码器，因为客户端只发送数据，不接收数据
                        }
                    });

            ChannelFuture f = b.connect("localhost", 8080).sync();

            // 发送消息
            ByteBuf buf = f.channel().alloc().buffer();
            buf.writeBytes("aa".getBytes());
            buf.writeByte((byte) 0x7E);
            buf.writeBytes("0022900008000010241902ff0001aa1f97010813ffff23122416564801ff0052b8ee4139ff".getBytes());
            f.channel().writeAndFlush(buf);

            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}